
import { loadModules } from 'esri-loader';
import MapTools from './mapTools';
import EsriJSONToGeoJSON from './EsriJSONToGeoJSON';

let mapTools;

const queryTask = {
    executeQueryTask: function(url, geometry, where, fields, returnGeometry, successFun){
        if(url && typeof url != 'string'){
            url = url.url;
        }

        loadModules(["esri/tasks/query", "esri/tasks/QueryTask"])
        .then(([Query, QueryTask]) => {
            let query = new Query();
            if(geometry) query.geometry = geometry;
            query.where = where? where : "1=1";
            query.outFields = fields?fields:["*"];
			query.returnGeometry = returnGeometry?true:false;
			// query.geometryPrecision = 0;
            // query.maxAllowableOffset = 1;
            
            let queryTask = new QueryTask(url);
            queryTask.execute(query, function(result){
                
                if(successFun && typeof successFun=='function'){
                    successFun(result);
                }
            })
			
        })
    },
    executeQueryFeatureLayer: function(layer, geometry, where, fields, returnGeometry, successFun){
        loadModules(["esri/layers/FeatureLayer", "esri/tasks/query"])
        .then(([FeatureLayer, Query]) => {
            let query = new Query();
            if(geometry) query.geometry = geometry;
            query.where = where? where : "1=1";
            query.outFields = fields?fields:["*"];
			query.returnGeometry = returnGeometry?true:false;
            layer && layer.queryFeatures(query, function(featureSet){
                if(successFun && typeof successFun=='function'){
                    successFun(featureSet);
                }
            }, function(e){
                console.log(e);
            })
        })

    },
    executeQueryLocal: function(layer, geometry, successFun) {
        
        if(!mapTools){
            mapTools = new MapTools();
        }

        let graphics = [];
        let gs = esri.getGeometries(layer.graphics);
        let intersect = mapTools.intersect(gs, geometry);
        for(let i=0;i<intersect.length;i++){
            if(intersect[i]){
                graphics.push(layer.graphics[i]);
            }
        }
        if(successFun && typeof successFun=='function'){
            successFun(graphics);
        }
        return graphics;
    }
}



export default queryTask;